import { Public } from '@/decorators/public.decorator';
import { LoginDTO } from '@/dtos/login.dto';
import { AuthService } from '@/services/auth.service';
import { getCookieExpireDate } from '@/util';
import {
  Body,
  Controller,
  Post,
  BadRequestException,
  Res,
  Req,
} from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('login')
  @Public()
  async signIn(
    @Body() loginDto: LoginDTO,
    @Res({ passthrough: true }) res: FastifyReply,
  ) {
    if (!loginDto?.username || !loginDto?.password) {
      throw new BadRequestException('用户名或密码不能为空！');
    }
    let { accessToken, refreshToken } = await this.authService.signIn(
      loginDto.username,
      loginDto.password,
    );
    res.setCookie('refresh_token', refreshToken, {
      path: '/',
      expires: getCookieExpireDate(2 * 12 * 60 * 60),
    });
    return accessToken;
  }

  @Post('refresh')
  @Public()
  async refresh(
    @Req() req: FastifyRequest,
    @Res({ passthrough: true }) res: FastifyReply,
  ) {
    let refreshToken = (req as any).cookies['refresh_token'];
    if (!refreshToken) {
      throw new BadRequestException('refreshToken不能为空！');
    }
    let { accessToken } = await this.authService.refresh(refreshToken);
    return accessToken;
  }
}
